﻿using System;
using System.Threading;
using NsbExtensions.Tests.Stubs;
using NUnit.Framework;

namespace NsbExtensions.Tests
{
    [TestFixture]
    public class BackgroundServiceTestFixture
    {
        [Test]
        public void BackgroundServiceTest()
        {
            const int iterations = 10;

            var service = new BusyBackgroundService();

            service.Start();

            service.DoWork(iterations);


            //wait for all the work to queue up
            while (Interlocked.Read(ref service.PendingWorkCount) < iterations)
                Thread.Sleep(10);

            //All work should be queued up, none completed
            Assert.AreEqual(0, service.WorkCompleteCount);
            Assert.AreEqual(iterations, service.PendingWorkCount);

            //Let 'er rip
            service.WorkQueue.Set();

            //Stop should not return until all work has been completed
            service.Stop();

            //Let's make sure it was all done, not as scrap left anywhere
            Assert.AreEqual(0, service.PendingWorkCount);
            Assert.AreEqual(iterations, service.WorkCompleteCount);
        }

        [Test]
        public void WorkWithoutStarting()
        {
            var service = new BusyBackgroundService();
            service.DoWork(1);
            service.Stop();
            Thread.Sleep(50);
            Assert.IsNotNull(service.Error);
            Assert.IsTrue(service.Error is InvalidOperationException);
        }
    }
}